#!/bin/bash
#==============================================================================
# 运行并验证所有案例do文件
# 作者：张立强
# 日期：2025-11-03
#==============================================================================

# 设置颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Stata路径
STATA_SE="/Applications/Stata/StataSE.app/Contents/MacOS/stata-se"
STATA_MP="/Applications/StataNow/StataMP.app/Contents/MacOS/stata-mp"

# 工作目录
WORK_DIR="/Users/mac/git/stata"
cd "$WORK_DIR"

# 创建输出目录
mkdir -p output/figures output/cases/figures output/logs

echo "================================================================================"
echo "案例代码验证和执行"
echo "================================================================================"
echo ""

# 案例列表
declare -a CASES=(
    "part1_basics/case01_salary_analysis.do:Stata SE:案例1-员工薪酬分析"
    "part1_basics/case02_house_price_prediction.do:Stata SE:案例2-房地产价格预测"
    "part2_regularization/case03_sales_forecasting.do:Stata SE:案例3-零售销售预测"
    "part2_regularization/case04_fifa_player_value.do:Stata MP:案例4-FIFA球员价值"
    "part3_advanced/case05_pricing_strategy.do:Stata MP:案例5-产品定价策略"
    "part4_comprehensive/case08_customer_lifetime_value.do:Stata MP:案例8-客户生命周期价值"
)

# 执行案例
for case_info in "${CASES[@]}"; do
    IFS=':' read -r case_file stata_type case_name <<< "$case_info"
    
    echo "--------------------------------------------------------------------------------"
    echo -e "${YELLOW}正在执行: $case_name${NC}"
    echo "文件: do/cases_by_chapter/$case_file"
    echo "Stata: $stata_type"
    echo "--------------------------------------------------------------------------------"
    
    # 选择Stata版本
    if [[ "$stata_type" == "Stata MP" ]]; then
        STATA_BIN="$STATA_MP"
    else
        STATA_BIN="$STATA_SE"
    fi
    
    # 检查Stata是否存在
    if [ ! -f "$STATA_BIN" ]; then
        echo -e "${RED}✗ Stata未找到: $STATA_BIN${NC}"
        continue
    fi
    
    # 执行do文件
    echo "开始执行..."
    "$STATA_BIN" -b do "do/cases_by_chapter/$case_file"
    
    # 检查执行结果
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ 执行成功${NC}"
    else
        echo -e "${RED}✗ 执行失败${NC}"
    fi
    
    echo ""
done

echo "================================================================================"
echo "执行完成"
echo "================================================================================"
echo ""
echo "日志文件位置: output/*.log"
echo "图表文件位置: output/figures/*.png"
echo ""

